#include <tsin/library/BulletTranslateEvent.hpp>

#include <tsin/runtime/BulletRuntime.hpp>

#include <cstring>
#define _USE_MATH_DEFINES
#include <cmath>

using namespace tsin;

BulletTranslateEvent::BulletTranslateEvent()
        : speed(0.0f), dangle(0.0f), starting(0.0f)
{
}

void BulletTranslateEvent::init(float speed, float dangle, float starting)
{
        if (starting != 0) {
                v = 0.0f;
                if (starting * speed < 0)
                        starting *= -1;
        } else
                v = speed;

        this->speed = speed;
        this->dangle = dangle;
        this->starting = starting;
}

void BulletTranslateEvent::reinit()
{
        float arg1 = arguments[0]->getFloat();
        float arg2 = arguments[1]->getFloatInRad();
        float arg3 = arguments[2]->getFloat();

        switch(nrArguments) {
        case 1:
                if (strcmp(desp, "N") == 0)
                        init(arg1);
                break;
        case 2:
                if (strcmp(desp, "NN") == 0)
                        init(arg1, arg2);
                break;
        case 3:
                if (strcmp(desp, "NNN") == 0)
                        init(arg1, arg2, arg3);
                break;
        }
}

bool BulletTranslateEvent::trigger(BulletRuntime &bullet, void *)
{
        return bullet.stage == BULLET_STAGE_LIVE;
}

BulletEvent *BulletTranslateEvent::handle(BulletRuntime &bullet, void *)
{
        if (v != speed) {
                v += starting;
                if ((starting < 0 && v < speed) || (starting > 0 && v > speed))
                        v = speed;
        }

        float sx = v * sin(bullet.direction), sy = v * cos(bullet.direction);
        bullet.x -= sx;
        bullet.y += sy;
        bullet.direction += dangle;
        bullet.angle = v > 0 ? bullet.direction : bullet.direction + M_PI;

        return this;
}
